package com.djmw.mouse.web.admin;

import java.util.Map;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.djmw.mouse.entity.Company;
import com.djmw.mouse.entity.HrUser;
import com.djmw.mouse.entity.Industry;
import com.djmw.mouse.service.CompanyService;
import com.djmw.mouse.service.IndustryService;
import com.djmw.mouse.service.account.HrAccountService;
import com.djmw.mouse.service.constants.Constants;
import com.google.common.collect.Maps;

/**
 * 公司管理的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /admin/company/ <br>
 * Create page : GET /admin/company/create <br>
 * Create action : POST /admin/company/create <br>
 * Update page : GET /admin/company/update/{id} <br>
 * Update action : POST /admin/company/update <br>
 * Delete action : GET /admin/company/delete/{id} <br>
 * 
 * @author michael
 */

@Controller
@RequestMapping(value = "/admin/company")
public class CompanyController {

    private static final int PAGE_SIZE = 20;

    private static Map<String, String> sortTypes = Maps.newLinkedHashMap();
    static {
        sortTypes.put("auto", "自动");
        sortTypes.put("name", "公司名称");
    }

    @Autowired
    private CompanyService companyService;
    @Autowired
    private IndustryService industryService;
    @Autowired
    private HrAccountService hrAccountService;
    @Autowired
    private Validator validator;

    @RequestMapping(value = "")
    public String list(@RequestParam(value = "sortType", defaultValue = "auto") String sortType,
            @RequestParam(value = "page", defaultValue = "1") int pageNumber, Model model, ServletRequest request) {
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page<Company> companys = companyService.getCompany(searchParams, pageNumber, PAGE_SIZE, sortType);

        model.addAttribute("companys", companys);
        model.addAttribute("sortType", sortType);
        model.addAttribute("sortTypes", sortTypes);
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));

        return "admin/company/company-list";
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String createForm(Model model) {
        model.addAttribute("company", new Company());
        model.addAttribute("companyTypes", Constants.COMPANY_TYPES);
        model.addAttribute("companySizes", Constants.COMPANY_SIZES);
        model.addAttribute("companyProvinces", Constants.PROVINCES);
        model.addAttribute("companyCities", Constants.CITIES);
        model.addAttribute("action", "create");
        return "admin/company/company-form";
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String create(@Valid Company newCompany, Long industryId, Long industry2Id,
            RedirectAttributes redirectAttributes) {
        Industry industry;
        if (industryId != null) {
            if ((industry = industryService.getIndustry(industryId)) != null) {
                newCompany.setIndustry(industry);
            }
        }
        if (industry2Id != null) {
            if ((industry = industryService.getIndustry(industry2Id)) != null) {
                newCompany.setIndustry2(industry);
            }
        }
        companyService.saveCompany(newCompany);
        redirectAttributes.addFlashAttribute("message", "创建公司成功");
        return "redirect:/admin/company/";
    }

    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("company", companyService.getCompany(id));
        model.addAttribute("companyTypes", Constants.COMPANY_TYPES);
        model.addAttribute("companySizes", Constants.COMPANY_SIZES);
        model.addAttribute("companyProvinces", Constants.PROVINCES);
        model.addAttribute("companyCities", Constants.CITIES);
        model.addAttribute("action", "update");
        return "admin/company/company-form";
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(@Valid @ModelAttribute("preloadCompany") Company company, Long industryId, Long industry2Id,
            RedirectAttributes redirectAttributes) {
        Industry industry;
        if (industryId != null) {
            if ((industry = industryService.getIndustry(industryId)) != null) {
                company.setIndustry(industry);
            }
        }
        if (industry2Id != null) {
            if ((industry = industryService.getIndustry(industry2Id)) != null) {
                company.setIndustry2(industry);
            }
        }
        companyService.saveCompany(company);
        redirectAttributes.addFlashAttribute("message", "更新公司成功");
        return "redirect:/admin/company/";
    }

    @RequestMapping(value = "delete/{id}")
    public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        companyService.deleteCompany(id);
        redirectAttributes.addFlashAttribute("message", "删除公司成功");
        return "redirect:/admin/company/";
    }

    @RequestMapping(value = "disable/{id}")
    public String disable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        companyService.changeCompanyStatus(id, Company.DISABLE);
        redirectAttributes.addFlashAttribute("message", "停用公司成功");
        return "redirect:/admin/company/";
    }

    @RequestMapping(value = "enable/{id}")
    public String enable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        companyService.changeCompanyStatus(id, Company.ENABLE);
        redirectAttributes.addFlashAttribute("message", "启用公司成功");
        return "redirect:/admin/company/";
    }

    @RequestMapping(value = "deposit/{id}", method = RequestMethod.GET)
    public String depositForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("company", companyService.getCompany(id));
        return "admin/company/company-deposit-form";
    }

    @RequestMapping(value = "deposit", method = RequestMethod.POST)
    public String deposit(Long id, Double amount, RedirectAttributes redirectAttributes) {
        companyService.deposit(id, amount);
        redirectAttributes.addFlashAttribute("message", "充值成功");
        return "redirect:/admin/company/";
    }

    @RequestMapping(value = "{id}/account", method = RequestMethod.GET)
    public String listAccount(@PathVariable("id") Long id, Model model) {
        model.addAttribute("hrAccounts", hrAccountService.getCompanyAccount(id));
        model.addAttribute("companyId", id);
        return "admin/company/company-account-list";
    }

    @RequestMapping(value = "{id}/account/register", method = RequestMethod.GET)
    public String createAccountForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("hrAccount", new HrUser());
        model.addAttribute("companyId", id);
        return "admin/company/company-account-register";
    }

    @RequestMapping(value = "{id}/account/register", method = RequestMethod.POST)
    public String create(@Valid HrUser user, @PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        user.setCompany(companyService.getCompany(id));
        hrAccountService.registerUser(user);
        redirectAttributes.addFlashAttribute("message", "创建账号成功");
        return "redirect:/admin/company/" + id + "/account";
    }

    @RequestMapping(value = "{id}/account/update/{aid}", method = RequestMethod.GET)
    public String updateAccountForm(@PathVariable("id") Long id, @PathVariable("aid") Long aid, Model model) {
        model.addAttribute("hrAccount", hrAccountService.getUser(aid));
        model.addAttribute("companyId", id);
        return "admin/company/company-account-profile";
    }

    @RequestMapping(value = "{id}/account/update", method = RequestMethod.POST)
    public String updateAccount(@Valid @ModelAttribute("preloadHrUser") HrUser user, @PathVariable("id") Long id,
            RedirectAttributes redirectAttributes) {
        user.setCompany(companyService.getCompany(id));
        hrAccountService.updateUser(user);
        redirectAttributes.addFlashAttribute("message", "更新账号成功");
        return "redirect:/admin/company/" + id + "/account";
    }

	                        /**
     * 使用@ModelAttribute, 实现Struts2
     * Preparable二次部分绑定的效果,先根据form的id从数据库查出Company对象,再把Form提交的内容绑定到该对象上。
     * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
     */
    @ModelAttribute("preloadCompany")
    public Company getCompany(@RequestParam(value = "id", required = false) Long id) {
        if (id != null) {
            return companyService.getCompany(id);
        }
        return null;
    }

    @ModelAttribute("preloadHrUser")
    public HrUser getHrUser(@RequestParam(value = "id", required = false) Long id) {
        if (id != null) {
            return hrAccountService.getUser(id);
        }
        return null;
    }
}
